package com.health.controller;

import com.health.annotation.AdminLog;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.health.common.Result;
import com.health.entity.Admin;
import com.health.entity.pojo.PageData;
import com.health.entity.pojo.dto.AdminDTO;
import com.health.entity.pojo.dto.DeleteAdminShelvesMultiDTO;
import com.health.entity.pojo.vo.AdminVO;
import com.health.entity.pojo.vo.QueryAdminVO;
import com.health.service.IAdminService;
import com.health.service.ITPermisionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 后台管理员表 前端控制器
 * </p>
 *
 * @author sanchuan
 * @since 2023-04-14
 */
@Api(tags = "管理员前端控制器")
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController extends  BaseController{

    @Autowired
    private IAdminService is;

    @Autowired
    private ITPermisionService ps;

    @ApiOperation("管理员登陆")
    @PostMapping("/login")
    @AdminLog("管理员登陆")
    public Result<Map<String,String>> login(@RequestBody Admin admin){
        this.logout();
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword());
            try {
                subject.login(token);
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return this.error();
            }
        }
        Map<String,Object> token = new HashMap<>();
        token.put("token",subject.getPrincipal());
        return this.dataResult(token);
    }

    @ApiOperation("获得管理员信息")
    @GetMapping("/info")
    @AdminLog("获得管理员信息")
    public Result<Map<String,String>>  getInfo(@RequestParam String token){

        AdminVO admin = is.findUserInfo(token);
        System.out.println("=================================" + admin);
        // 获得button权限
        Set<String> permissions = ps.findPermissionsByAccount(token);
        Map<String, Object> info = new HashMap<>();

        // 传roles数组回前端
        List<String> roles = new ArrayList<>();
        roles.add(admin.getRoles());

        info.put("roles", roles);
        info.put("name", admin.getName());
        info.put("avatar", admin.getAvatar());
        info.put("perms",permissions);


        return this.dataResult(info);
    }

    @ApiOperation("管理员注销登录")
    @PostMapping("/logout")
    @AdminLog("管理员注销登录")
    public Result<String> logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return this.dataResult("注销登陆成功");
    }

    @ApiOperation("获得后台账号列表分页+条件查询")
    @PostMapping("/listAdminPage/{pageNum}/{pageSize}")
    public Result listAdminPage(
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize,
            @RequestBody AdminDTO adminDTO){
        IPage<QueryAdminVO> adminIPage = is.listAdminPage(pageNum, pageSize, adminDTO);
        return this.dataResult(adminIPage);
    }

    @ApiOperation("添加管理人员")
    @PostMapping("/addAdmin/{type}")
    @Transactional
    public Result<Boolean> addAdmin(@RequestBody Admin admin,@PathVariable("type") String type){
        Boolean b = is.saveOrUpdate(admin);
        Boolean result = null;
        if (type.equals("add")){
            result = is.saveAdminRole(admin.getId(),admin.getRoleId());
        }else if (type.equals("edit")){
            result = is.upadteAdminRole(admin.getId(),admin.getRoleId());
        }
        return this.dataResult(result);
    }

    @ApiOperation("根据ID查找管理人员")
    @GetMapping("/getAdminById/{id}")
    public Result<Admin> getAdminById(@PathVariable("id") Integer id){
        return this.dataResult(is.getById(id));
    }

    @ApiOperation("根据ID删除管理人员")
    @DeleteMapping("/deletedminById/{id}/{rid}")
    @Transactional
    public Result<Boolean> deletedminById(@PathVariable("id") Integer id,@PathVariable("rid") Integer rid){
        is.removeById(id);
        Boolean result = is.deleteAdminRole(id,rid);
        return this.dataResult(result);
    }

    @ApiOperation("批量删除管理人员")
    @DeleteMapping("/deleteAdminShelvesMulti")
    @Transactional
    public Result<Boolean> deleteAdminShelvesMulti(@RequestBody List<DeleteAdminShelvesMultiDTO> selectedData){
        List<Integer> ids = new ArrayList<>();
        selectedData.forEach(item ->{
            ids.add(item.getId());
        });
        is.removeByIds(ids);
        Boolean result =  is.deleteAdminRoleMulti(selectedData);
        return this.dataResult(result);
    }
}
